var tree, zNodes , citylist;

var setting = {
	data : {
		simpleData : {
			enable : true,
			idKey : "departmentid",
			pIdKey : "pid"
		},
		view : {
			dblClickExpand : false,
			selectedMulti : false
		},
		key : {
			name : "mc"
		}
	},
	callback : {
		onRightClick : function(event, treeId, treeNode) {
			if (treeNode && !treeNode.noR) {
				tree.selectNode(treeNode);
				$('#mm').menu('show', {
					left : event.pageX,
					top : event.pageY
				});
			}
			$('#mm').menu({
				onClick : function(item) {
					if (item.name == "addDept") {
						openDialog("添加部门", "270", "130", "addDept");
					}
					if (item.name == "updateDept") {
						openDialog("修改部门", "270", "130", "updateDept");
						getDept(tree.getSelectedNodes()[0].departmentid);
					}
					if (item.name == "delDept") {
						delDept();
					}
				}
			});
		},
		onClick : function(event, treeId, treeNode) {
			$('#deptDatagridMenus').find('a').linkbutton('enable');
			$("#deptDatagrid").datagrid({
				url : "/rbac/getUsersBydeptid",
				queryParams : {
					'deptid' : treeNode.departmentid
				}
			});
		}
	}
};

$(document).ready(function() {
	$('#deptDatagridMenus').find('a').linkbutton('disable');
	$('#deptSort').numberspinner({
		min : 1,
		max : 10000
	});
	$.getJSON("/rbac/getallRoleforSel", function(json) {
		var height = json.msg.length > 6 ? "200" : "auto";
		$('#role').combobox({
			data : json.msg,
			valueField : 'id',
			textField : 'rolename',
			panelHeight : height,
			required : true,
			editable : false,
			onLoadError : function() {
				alert("读取错误，请刷新");
			}
		});
	});
	
/*	//所在区县添加显示选择
	$('#qxdm').combobox({
	    url:'/admin/getAllXzqhTypeForSel',
	    valueField:'qhbm',
	    textField:'qhmc',
	    ///自动完成
	    filter: function(q, row){
			var opts = $(this).combobox('options');
			return row[opts.textField].indexOf(q) == 0;
		}
	
	});*/
	//特惠商户所在区县JSON显示
/*	$.ajax({
		type : "POST",
		url : "/admin/getAllXzqhTypeForSel",
		data : {
			type : "402882654c65b5c7014c65d954b60000"
		},
		dataType : "json",
		success : function(result) {
			citylist = result;
		}
		
	});*/

	$('#userstate').combobox({
		data : [ {
			"id" : '正常',
			"name" : '正常'
		}, {
			"id" : '禁用',
			"name" : '禁用'
		} ],
		valueField : 'id',
		textField : 'name',
		panelHeight : "auto",
		required : true,
		editable : false,
		onLoadError : function() {
			alert("读取错误，请刷新");
		}
	});

	$('#username').textbox({
		iconCls : 'icon-man',
		iconAlign : 'left',
		required : true
	});
	$('#userpass').textbox({
		iconCls : 'icon-lock',
		iconAlign : 'left',
		required : true,
		type : "password"
	});
	
/*	$('#cell').textbox({
		iconCls : 'icon-man',
		iconAlign : 'left',
		required : true,
		
	});*/

/*	$('#email').textbox({
		iconCls : 'icon-man',
		iconAlign : 'left',
		required : true,
		
	});*/
	
/*	$('#remark').textbox({
		iconCls : 'icon-man',
		iconAlign : 'left',
		required : true,
		height:50
		
	});*/
	$('#deptSort').numberspinner('setValue', 1);
	getZtreeData();
	tree = $.fn.zTree.init($("#tree"), setting, zNodes);
	$("#ztreePanel").panel({
		width : 250,
		height : getWindowSize()[1] - 20,
		title : "部门列表",
		tools : [ {
			iconCls : 'icon-add',
			handler : function() {
				openDialog("添加根部门", "270", "130", "addTopDept");
			}
		} ]
	});
	$("#ztreePanel").panel('refresh');

	getdeptDatagrid();
	
	
	
	
	
	

});

//获得部门表数据
function getZtreeData() {
	
	$.ajax({
		type : "post",
		async : false,
		url : "/rbac/getAlldepartment",
		dataType : "json",
		success : function(result) {
			zNodes = result.rows;
		}
	});
	tree = $.fn.zTree.init($("#tree"), setting, zNodes);
}

function getdeptDatagrid() {
	$('#deptDatagrid').datagrid({
		title : '部门人员',
		width : getWindowSize()[0] - 260,
		height : getWindowSize()[1] - 10,
		loadMsg : '装载中...',
		nowrap : true, // 如果为true，则在同一行中显示数据。设置为true可以提高加载性能。
		striped : true, // 显示斑马线效果
		// collapsible : true, //显示可折叠按钮
		checkbox : true, // 显示复选框
		fitColumns : true, // 适应网格的宽度，防止水平滚动
		singleSelect : true, // 只允许选择一行
		rownumbers : true, // 显示一个行号列
		remoteSort : false, // 从服务器对数据进行排序
		pagination : true, // 显示分页工具栏
		checkOnSelect : true, // 当用户点击行的时候该复选框就会被选中或取消选中
		pageList : [ 10, 50, 100, 200 ], // 页面大小选择列表
		columns : [ [ {
			field : 'id',
			title : 'ID',
			width : 100,
			align : 'center',
			checkbox : true
		}, {
			field : 'username',
			title : '姓名',
			width : 100,
			align : 'center',
			sortable : true
		}, {
			field : 'roleid',
			title : '岗位',
			width : 100,
			align : 'center',
			sortable : true
		}, {
			field : 'state',
			title : '状态',
			width : 100,
			align : 'center',
			sortable : true
		} 
		/*, {
			field : 'cell',
			title : '手机号码',
			width : 100,
			align : 'center',
			sortable : true
		} 
		, {
			field : 'email',
			title : '电子邮件',
			width : 100,
			align : 'center',
			sortable : true
		} 
		,{
			field : 'qxdm',
			title : '所在区县',
			width : 150,
			align : 'center',
			sortable : true,
			formatter:function(value){
				for(var i in citylist){
					if (citylist[i].qhbm == value){
						return citylist[i].qhmc;
					}
				}
	        }
		}, 
		{
			field : 'remark',
			title : '备注',
			width : 100,
			align : 'center',
			sortable : true
		} */
		
		
		
		
		/*,
										{
											field : 'opt',
											title : '操作',
											width : 300,
											align : 'center',
											sortable : true,
											formatter : function(value, row, index) {

												return '<a href="javascript:void(0);" id="DataAdd" onclick="behaviorAuthorization(\''
														+ row.id
														+ '\');">行为授权</a>&nbsp;'
														+ '<a href="javascript:void(0);" id="DataAdd" onclick="menuAuthorization(\''
														+ row.id
														+ '\');">菜单授权</a>&nbsp;'
														+ '<a href="javascript:void(0);" id="DataAdd" onclick="articleCategoryAuthorization(\''
														+ row.id + '\');">文章类目授权</a>';
											}
										}*/] ],
		toolbar : '#deptDatagridMenus',
		onDblClickCell : function() {
			// var row = $('#gzrllb').datagrid('getSelected');
		}
	});
}

function openpersonnelDialog(title) {
	clearCachePersonnelDialog();
	$('#personnelDialog').dialog({
		title : title,
		width : 280,
		height : 380,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '保存',
			handler : function() {
				if ($("#userid").val() == "") {
					addUsers();
				} else {
					updateUsers();
				}
			}
		}, {
			text : '关闭',
			handler : function() {
				$('#personnelDialog').window('close');
			}
		} ]
	});
}

function clearCachePersonnelDialog() {
	$('#userid').val("");
	$('#userpass,#username').textbox('setText', "");
	$('#role,#userstate').combobox('setValue', '');
	//$('#cell,#email,#remark').val("");
	id_ = "";
	pid_ = "";
	
}

function getRole() {
	$.ajax({
		type : "post",
		url : "/rbac/getallRoleforSel",
		dataType : "json",
		success : function(result) {

		}
	});
}






/*private String id;
 private String username;
 private String pass;
 private String dpid;
 private String roleid;
 private String state;*/
function addUsers() {
	//	tree.getSelectedNodes()[0].getParentNode().id,
	
	var isValid = $('#personnelForm').form('validate');
	//alert(isValid);
	if(isValid){
           
		var username=$('#username').textbox('getText');
		var dpid=tree.getSelectedNodes()[0].departmentid;
		var roleid=$('#role').combobox('getValue');
		var pass=$('#userpass').textbox('getText');
		var state=$('#userstate').combobox('getValue');
		//var qxdm=$('#qxdm').combobox('getValue');
		//var cell=$('#cell').textbox('getText');
		//var email=$('#email').textbox('getText');
		//var remark=$('#remark').textbox('getText');
		
	$.ajax({
		type : "post",
		url : "/rbac/addUsers",
		data : {
			"user.username" :username ,
			"user.pass" :pass ,
			"user.dpid" :dpid ,
			"user.roleid" : roleid,
			"user.state" : state
			//"users.qxdm" : qxdm,
			//"users.cell" : cell,
			//"users.email" : email,
			//"users.remark" : remark
		},
		dataType : "json",
		success : function(result) {
			if (result.msg == "ok") {
				$('#deptDatagrid').datagrid('reload');
				$('#personnelDialog').window('close');
			
			}
			else{
				$.messager.show({
					title:'提示',
					msg:result.msg,
					showType:'fade',
					delay : 1000,
					style:{
						right:'',
						bottom:''
					}
				});
			}
		}
	});
	}
	else{
		
		$.messager.show({
			title:'提示',
			msg:"用户名已经被占用，请跟换用户名再提交",
			showType:'fade',
			delay : 1000,
			style:{
				right:'',
				bottom:''
			}
		});
	}
}
		

function getUsers() {
	var rows = $("#deptDatagrid").datagrid("getSelections");
	if (rows == null || rows == "" || rows.length > 1) {
		$.messager.alert('警告', '请选中一行!', 'warning');
		return;
	}
	openpersonnelDialog('修改');

	$.ajax({
		type : "post",
		url : "/rbac/getSingleUser",
		data : {
			"user.id" : rows[0].id
		},
		dataType : "json",
		success : function(result) {
			$('#username').textbox('setText', result.msg.username);
			$('#userpass').textbox('setText', result.msg.pass);
			pid_ = result.msg.dpid;
			$("#userid").val(result.msg.id);
			$('#role').combobox('setValue', result.msg.roleid);
			$('#userstate').combobox('setValue', result.msg.state);
//			$('#qxdm').combobox('setValue', result.msg.qxdm);
//			$('#cell').textbox('setText', result.msg.cell);
//			$('#email').textbox('setText', result.msg.email);
//			$('#remark').textbox('setText', result.msg.remark);
		}
	});
}

function updateUsers() {
	$.ajax({
		type : "post",
		url : "/rbac/updateUser",
		data : {
			"user.id" : $("#userid").val(),
			"user.username" : $('#username').textbox('getText'),
			"user.pass" : $('#userpass').textbox('getText'),
			"user.dpid" : pid_,
			"user.roleid" : $('#role').combobox('getValue'),
			"user.state" : $('#userstate').combobox('getValue')
			//"users.qxdm" : $('#qxdm').combobox('getValue'),
			//"users.cell" : $('#cell').textbox('getText'),
			//"users.email" : $('#email').textbox('getText'),
			//"users.remark" : $('#remark').textbox('getText')
		},
		dataType : "json",
		success : function(result) {
			if (result.msg == "ok") {
				$('#deptDatagrid').datagrid('reload');
				$('#personnelDialog').window('close');
			}
		}
	});
}

function delUsers() {
	var rows = $("#deptDatagrid").datagrid("getSelections");
	if (rows == null || rows == "") {
		$.messager.alert('警告', '请选中一行!', 'warning');
		return;
	}
	var list_ = {};
	for (var i = 0; i < rows.length; i++) {
		list_["user[" + i + "].id"] = rows[i].id;
	}
	$.messager.confirm('确认', '您确认想要删除记录吗？', function(r) {
		if (r) {
			$.ajax({
				type : "POST",
				url : "/rbac/deleteUser",
				data : {
					"user.id":rows[0].id
				},
				dataType : "json",
				// traditional: true,
				success : function(result) {
					if (result.msg == "ok") {
						$('#deptDatagrid').datagrid('reload');
					}
				}
			});
		}
	});
}

function openDialog(title, width, height, name) {
	clearCache();
	$('#dialog').dialog({
		title : title,
		width : width,
		height : height,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '保存',
			handler : function() {
				if (name == "addDept") {
					addDept("addDept");
				}
				if (name == "addTopDept") {
					addDept("addTopDept");
				}
				if (name == "updateDept") {
					updateDept();
				}
			}
		}, {
			text : '关闭',
			handler : function() {
				$('#dialog').window('close');
			}
		} ]
	});
}

function clearCache() {
	$("#deptName,#deptSort").val("");
	id_ = "";
	pid_ = "";
}

function addDept(val) {
	if (val == "addTopDept") {
		$.ajax({
			type : "post",
			url : "/rbac/addDept",
			data : {
				"dept.mc" : $("#deptName").val(),
				"dept.nj" : $('#deptSort').numberspinner('getValue')
			},
			dataType : "json",
			success : function(result) {
				if (result.msg == "ok") {
					getZtreeData();
					$('#dialog').window('close');
				}
			}
		});
	}
	if (val == "addDept") {
		$.ajax({
			type : "post",
			url : "/rbac/addDept",
			data : {
				"dept.mc" : $("#deptName").val(),
				"dept.pid" : tree.getSelectedNodes()[0].departmentid,
				"dept.nj" : $('#deptSort').numberspinner('getValue')
			},
			dataType : "json",
			success : function(result) {
				if (result.msg == "ok") {
					getZtreeData();
					$('#dialog').window('close');
				}
			}
		});
	}
}
var id_ = "", pid_ = "";
function getDept(id) {
	$.ajax({
		type : "post",
		async : false,
		url : "/rbac/getSingleDepartment",
		data : {
			"dept.departmentid" : id
		},
		dataType : "json",
		success : function(result) {
			$("#deptName").val(result.msg.mc);
			$('#deptSort').numberspinner('setValue', result.msg.nj);
			pid_ = result.msg.pid;
			id_ = result.msg.departmentid;
		}
	});
}

function updateDept() {
	$.ajax({
		type : "post",
		url : "/rbac/updateDepartment",
		data : {
			"dept.departmentid" : id_,
			"dept.mc" : $("#deptName").val(),
			"dept.pid" : pid_,
			"dept.nj" : $('#deptSort').numberspinner('getValue')
		},
		dataType : "json",
		success : function(result) {
			if (result.msg == "ok") {
				getZtreeData();
				$('#dialog').window('close');
			}
		}
	});
}

function delDept() {
	if (tree.getSelectedNodes()[0].isParent) {
		$.messager.alert('错误', '该节点下存在子节点，请先删除子节点!', 'warning');
	} else {
		$.ajax({
			type : "post",
			url : "/rbac/deleteDept",
			data : {
				"dept.departmentid" : tree.getSelectedNodes()[0].departmentid
			},
			dataType : "json",
			success : function(result) {
				if (result.msg == "ok") {
					getZtreeData();
				}
			}
		});
	}
}

window.onresize = function() {
	$("#ztreePanel").panel({
		height : getWindowSize()[1] - 20
	});
};

function getWindowSize() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement
			&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body
			&& (document.body.clientWidth || document.body.clientHeight)) {
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return ([ myWidth, myHeight ]);
}

